/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.financial.web.lettercredit;

import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.lang.NumberUtils;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.base.entity.cars.Tcar;
import com.jeesite.modules.base.entity.supplier.Supplier;
import com.jeesite.modules.base.service.cars.TcarService;
import com.jeesite.modules.base.service.supplier.SupplierService;
import com.jeesite.modules.custom.enumInfo.supplierTypeEnum;
import com.jeesite.modules.custom.service.CodeRuleService;
import com.jeesite.modules.financial.dao.lettercredit.LetterCreditDetailDao;
import com.jeesite.modules.financial.entity.lettercredit.LetterCredit;
import com.jeesite.modules.financial.entity.lettercredit.LetterCreditDetail;
import com.jeesite.modules.financial.service.lettercredit.LetterCreditService;
import com.jeesite.modules.order.entity.serviceorder.ServiceOrder;
import com.jeesite.modules.order.entity.serviceorder.ServiceOrderDetail;
import com.jeesite.modules.order.service.serviceorder.ServiceOrderService;
import com.jeesite.modules.sys.entity.EmpUser;
import com.jeesite.modules.sys.service.EmpUserService;
import com.jeesite.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.List;

/**
 * 信用证Controller
 * @author Kilo
 * @version 2021-03-09
 */
@Controller
@RequestMapping(value = "${adminPath}/financial/lettercredit/letterCredit")
public class LetterCreditController extends BaseController {

	@Autowired
	private LetterCreditService letterCreditService;
	@Autowired
	private SupplierService supplierService;
	@Autowired
	private TcarService tcarService;
	@Autowired
	private ServiceOrderService serviceOrderService;
	@Autowired
	private CodeRuleService codeRuleService;
	@Autowired
	private EmpUserService empUserService;
	@Autowired
	private LetterCreditDetailDao letterCreditDetailDao;
	/**
	 * 获取数据
	 */
	@ModelAttribute
	public LetterCredit get(String letterCreditId, boolean isNewRecord) {
		return letterCreditService.get(letterCreditId, isNewRecord);
	}
	
	/**
	 * 查询列表
	 */
	@RequiresPermissions("financial:lettercredit:letterCredit:view")
	@RequestMapping(value = {"list", ""})
	public String list(LetterCredit letterCredit, Model model) {
		model.addAttribute("letterCredit", letterCredit);
		// 供应商
		List<Supplier> supplierList = supplierService.findList(new Supplier());
		model.addAttribute("supplierList", supplierList);
		// 海外资方
		Supplier hwzf = new Supplier();
		hwzf.setSupplierType("2");
		List<Supplier> hwzfList = supplierService.findList(hwzf);
		model.addAttribute("hwzfList", hwzfList);
		// 国内资方
		Supplier gnzf = new Supplier();
		gnzf.setSupplierType("1");
		List<Supplier> gnzfList = supplierService.findList(gnzf);
		model.addAttribute("gnzfList", gnzfList);
		// 车辆
		List<Tcar> tcarList = tcarService.findList(new Tcar());
		Tcar tcar = new Tcar();
		tcar.setCarName("");
		tcar.setCarId("");
		tcarList.add(tcar);
		model.addAttribute("tcarList", tcarList);
		model.addAttribute("listUser", empUserService.findList(new EmpUser()));
		model.addAttribute("listServiceOrder", serviceOrderService.findList(new ServiceOrder()));// 服务订单号
		return "modules/financial/lettercredit/letterCreditList";
	}
	
	/**
	 * 查询列表数据
	 */
	@RequiresPermissions("financial:lettercredit:letterCredit:view")
	@RequestMapping(value = "listData")
	@ResponseBody
	public Page<LetterCredit> listData(LetterCredit letterCredit, HttpServletRequest request, HttpServletResponse response) {
		letterCredit.setPage(new Page<>(request, response));
		Page<LetterCredit> page = letterCreditService.findPage(letterCredit);
		return page;
	}

	/**
	 * 查看编辑表单
	 */
	@RequiresPermissions("financial:lettercredit:letterCredit:view")
	@RequestMapping(value = "form")
	public String form(LetterCredit letterCredit, Model model) {
		model.addAttribute("letterCredit", letterCredit);
		// 供应商
		List<Supplier> supplierList = supplierService.findList(new Supplier());
		model.addAttribute("supplierList", supplierList);
        // 海外资方
        Supplier hwzf = new Supplier();
        hwzf.setSupplierType(supplierTypeEnum.FOR_SUPPLIER.getCode());
        List<Supplier> hwzfList = supplierService.findList(hwzf);
        // 供货外商
        Supplier ghws = new Supplier();
        ghws.setSupplierType(supplierTypeEnum.SUPPLIER.getCode());
        List<Supplier> ghwsList = supplierService.findList(ghws);
        model.addAttribute("ghwsList", ghwsList);
        hwzfList.addAll(ghwsList);
        model.addAttribute("hwzfList", hwzfList);
		// 国内资方
		Supplier gnzf = new Supplier();
		gnzf.setSupplierType(supplierTypeEnum.IN_SUPPLIER.getCode());
		List<Supplier> gnzfList = supplierService.findList(gnzf);
		model.addAttribute("gnzfList", gnzfList);
		// 车辆
		List<Tcar> tcarList = tcarService.findList(new Tcar());
		Tcar tcar = new Tcar();
		tcar.setCarName("");
		tcar.setCarId("");
		tcarList.add(tcar);
		model.addAttribute("tcarList", tcarList);
		model.addAttribute("listServiceOrder", serviceOrderService.findList(new ServiceOrder()));// 服务订单号
		return "modules/financial/lettercredit/letterCreditForm";
	}

	/**
	 * 查看表单详情
	 */
	@RequiresPermissions("financial:lettercredit:letterCredit:view")
	@RequestMapping(value = "detail")
	public String detail(LetterCredit letterCredit, Model model) {
		model.addAttribute("letterCredit", letterCredit);
		// 供应商
		List<Supplier> supplierList = supplierService.findList(new Supplier());
		model.addAttribute("supplierList", supplierList);
        // 海外资方
        Supplier hwzf = new Supplier();
        hwzf.setSupplierType(supplierTypeEnum.FOR_SUPPLIER.getCode());
        List<Supplier> hwzfList = supplierService.findList(hwzf);
        // 供货外商
        Supplier ghws = new Supplier();
        ghws.setSupplierType(supplierTypeEnum.SUPPLIER.getCode());
        List<Supplier> ghwsList = supplierService.findList(ghws);
        model.addAttribute("ghwsList", ghwsList);
        hwzfList.addAll(ghwsList);
        model.addAttribute("hwzfList", hwzfList);
		// 国内资方
		Supplier gnzf = new Supplier();
		gnzf.setSupplierType("1");
		List<Supplier> gnzfList = supplierService.findList(gnzf);
		model.addAttribute("gnzfList", gnzfList);
		// 车辆
		List<Tcar> tcarList = tcarService.findList(new Tcar());
		Tcar tcar = new Tcar();
		tcar.setCarName("");
		tcar.setCarId("");
		tcarList.add(tcar);
		model.addAttribute("tcarList", tcarList);
		model.addAttribute("listServiceOrder", serviceOrderService.findList(new ServiceOrder()));// 服务订单号
		return "modules/financial/lettercredit/letterCreditDetail";
	}

	/**
	 * 保存数据
	 */
	@RequiresPermissions("financial:lettercredit:letterCredit:edit")
	@PostMapping(value = "save")
	@ResponseBody
	@Transactional(readOnly=false)
	public String save(@Validated LetterCredit letterCredit) {
		if(letterCredit.getIsNewRecord()){
			letterCredit.setLetterCreditCode(codeRuleService.getCode("LetterCredit"));
			letterCredit.setCreateBy(UserUtils.getUser().getLoginCode());
			letterCredit.setVersion(1L);
		}
		letterCreditService.save(letterCredit);
		if (letterCredit.getIsNewRecord()){
			codeRuleService.updateCurrentNumber("LetterCredit");
			//信用证编号回写服务订单
			ServiceOrder serviceOrder=serviceOrderService.get(letterCredit.getServiceOrderId());
			serviceOrder.setLetterCreditCode(letterCredit.getLetterCreditId());
			serviceOrderService.update(serviceOrder);
		}
		return renderResult(Global.TRUE, text("保存信用证成功！"));
	}
	
	/**
	 * 删除数据
	 */
	@RequiresPermissions("financial:lettercredit:letterCredit:delete")
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(LetterCredit letterCredit) {
		letterCreditService.delete(letterCredit);
		return renderResult(Global.TRUE, text("删除信用证成功！"));
	}

	/**
	 * 服务订单开信用证按钮
	 */
	@RequiresPermissions("financial:lettercredit:letterCredit:edit")
	@RequestMapping(value = "goLetterCredit")
	public String goLetterCredit(ServiceOrder serviceOrder, Model model) {
		ServiceOrder so = serviceOrderService.get(serviceOrder);
		LetterCredit letterCredit = new LetterCredit();
		letterCredit.setServiceOrderId(so.getServiceOrderId());
		letterCredit.setCustomer(so.getCustomer());
		letterCredit.setInvestorId(so.getInvestorId());
		letterCredit.setForeignBusinessmenId(so.getForeignBusinessmenId());
		letterCredit.setSupplierAddress(supplierService.get(so.getForeignBusinessmen()).getAddress());
		letterCredit.setSupplierId(so.getSupplierId());
		letterCredit.setEntrustAgreement(so.getPurchaseCommissionNumber());
		letterCredit.setTradeTerm(so.getTradeTerm());
		letterCredit.setForeignTradeContractNumber(so.getForeignTradeContractNumber());
		letterCredit.setOrderStatus("1");
		letterCredit.setRatio(so.getNegotiatedRatioId());
		letterCredit.setPaymentMethod(so.getPaymentMethod());
		letterCredit.setLatestShipmentDate(so.getLatestShipmentDate());
		letterCredit.setFromPort(so.getFromPort());
		letterCredit.setToPort(so.getToPort());
		letterCredit.setCurrency(so.getCurrency());

		Double total = 0D;
		for (ServiceOrderDetail serviceOrderDetail : so.getServiceOrderDetailList()) {
			LetterCreditDetail letterCreditDetail = new LetterCreditDetail();
			letterCreditDetail.setCarId(serviceOrderDetail.getCarId());
			letterCreditDetail.setTcar(serviceOrderDetail.getTcar());
			letterCreditDetail.setBrand(serviceOrderDetail.getBrand());
			letterCreditDetail.setArea(serviceOrderDetail.getArea());
			letterCreditDetail.setModel(serviceOrderDetail.getModel());
			letterCreditDetail.setQuantity(serviceOrderDetail.getQuantity());
			letterCreditDetail.setUnitPrice(serviceOrderDetail.getUnitPrice());
			letterCreditDetail.setAmount(serviceOrderDetail.getAmount());
			if(so.getNegotiatedRatioId() != null){
				letterCreditDetail.setNegotiatedAmount(NumberUtils.div(NumberUtils.mul(serviceOrderDetail.getAmount(),Double.parseDouble(so.getNegotiatedRatioId())), 100D, 2));
			}
			letterCreditDetail.setStatus1("1");
			letterCredit.getLetterCreditDetailList().add(letterCreditDetail);
			total = NumberUtils.add(total, serviceOrderDetail.getAmount());
		}
		total=NumberUtils.mul(total/100,Double.parseDouble(so.getNegotiatedRatioId()));
		letterCredit.setTotalAmount(total);
		model.addAttribute("letterCredit", letterCredit);
		// 供应商
		List<Supplier> supplierList = supplierService.findList(new Supplier());
		model.addAttribute("supplierList", supplierList);
        // 海外资方
        Supplier hwzf = new Supplier();
        hwzf.setSupplierType(supplierTypeEnum.FOR_SUPPLIER.getCode());
        List<Supplier> hwzfList = supplierService.findList(hwzf);
        // 供货外商
        Supplier ghws = new Supplier();
        ghws.setSupplierType(supplierTypeEnum.SUPPLIER.getCode());
        List<Supplier> ghwsList = supplierService.findList(ghws);
        model.addAttribute("ghwsList", ghwsList);
        hwzfList.addAll(ghwsList);
        model.addAttribute("hwzfList", hwzfList);
		// 国内资方
		Supplier gnzf = new Supplier();
		gnzf.setSupplierType("1");
		List<Supplier> gnzfList = supplierService.findList(gnzf);
		model.addAttribute("gnzfList", gnzfList);
		// 车辆
		List<Tcar> tcarList = tcarService.findList(new Tcar());
		Tcar tcar = new Tcar();
		tcar.setCarName("");
		tcar.setCarId("");
		tcarList.add(tcar);
		model.addAttribute("tcarList", tcarList);
		model.addAttribute("listServiceOrder", serviceOrderService.findList(new ServiceOrder()));// 服务订单号
		return "modules/financial/lettercredit/letterCreditForm";
	}

	/**
	 * 取消
	 * @param letterCreditId
	 */
	@RequestMapping(value = "cancel")
	@ResponseBody
	public String cancel(@RequestParam("letterCreditId") String letterCreditId) {
		LetterCredit letterCredit = new LetterCredit();
		letterCredit.setLetterCreditId(letterCreditId);
		letterCredit.setOrderStatus("3");
		letterCreditService.update(letterCredit);
		return renderResult(Global.TRUE, text("取消成功！"));
	}

	/**
	 * 撤证
	 * @param letterCreditId
	 */
	@RequestMapping(value = "revoke")
	@ResponseBody
	public String revoke(@RequestParam("letterCreditId") String letterCreditId) {
		LetterCredit letterCredit = new LetterCredit();
		letterCredit.setLetterCreditId(letterCreditId);
		letterCredit.setOrderStatus("4");
		letterCreditService.update(letterCredit);
		return renderResult(Global.TRUE, text("撤证成功！"));
	}

	/**
	 * 生效
	 * @param letterCreditId
	 */
	@RequestMapping(value = "submit")
	@ResponseBody
	@Transactional(readOnly=false)
	public String submit(@RequestParam("letterCreditId") String letterCreditId) {
		LetterCredit letterCredit = new LetterCredit();
		letterCredit.setLetterCreditId(letterCreditId);
		letterCredit.setOrderStatus("2");
		letterCreditService.update(letterCredit);
		ServiceOrder serviceOrder = new ServiceOrder();
		serviceOrder.setServiceOrderCode(letterCredit.getServiceOrderId());
		serviceOrder.setServiceOrderId(serviceOrderService.findList(serviceOrder).get(0).getServiceOrderId());
		serviceOrder.setLetterCreditCode(letterCreditId);
		serviceOrderService.update(serviceOrder);
		return renderResult(Global.TRUE, text("生效成功！"));
	}

	/**
	 * 已预投保
	 * @param letterCreditId
	 */
	@RequestMapping(value = "changeYTB")
	@ResponseBody
	public String changeYTB(@RequestParam("letterCreditId") String letterCreditId) {
		LetterCredit letterCredit = new LetterCredit();
		letterCredit.setLetterCreditId(letterCreditId);
		letterCredit.setPreInsuredFlag("1");
		letterCreditService.update(letterCredit);
		return renderResult(Global.TRUE, text("已预投保成功！"));
	}

	/**
	 * 更新版本
	 * @param letterCreditId
	 */
	@RequestMapping(value = "updateVersion")
	@ResponseBody
	@Transactional(readOnly=false)
	public String updateVersion(@RequestParam("letterCreditId") String letterCreditId) {
		LetterCredit letterCredit = new LetterCredit();
		letterCredit.setLetterCreditId(letterCreditId);
		LetterCredit lc = letterCreditService.get(letterCredit);
		LetterCredit oldLetterCredit = deepClone(lc);
		oldLetterCredit.setLetterCreditId("");
		oldLetterCredit.setOrderStatus("5");
		for (LetterCreditDetail letterCreditDetail : oldLetterCredit.getLetterCreditDetailList()) {
			letterCreditDetail.setIsNewRecord(true);
			letterCreditDetail.setLetterCreditDetailId("");
		}
		letterCreditService.save(oldLetterCredit);
		lc.setVersion(lc.getVersion()+1);
		letterCreditService.update(lc);
		return renderResult(Global.TRUE, text("更新版本成功！"));
	}

	public static LetterCredit deepClone(LetterCredit object) {
		try {
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
			ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
			objectOutputStream.writeObject(object);
			ByteArrayInputStream bais = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
			ObjectInputStream objectInputStream = new ObjectInputStream(bais);
			return (LetterCredit) objectInputStream.readObject();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 行状态改为取消
	 * @param serviceOrderDetailId
	 */
	@RequestMapping(value = "changeRowStatus")
	@ResponseBody
	public String changeRowStatus(@RequestParam("serviceOrderDetailId") String serviceOrderDetailId) {
		LetterCreditDetail letterCreditDetail = new LetterCreditDetail();
		letterCreditDetail.setLetterCreditDetailId(serviceOrderDetailId);
		letterCreditDetail.setStatus1("3");
		letterCreditDetailDao.update(letterCreditDetail);
		return renderResult(Global.TRUE, text("状态取消成功！"));
	}
}